//
//  AddressBookHelper.swift
//  Employee
//
//  Created by swordjoy on 2017/3/22.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import Foundation

struct AddressBookHelper {
  /// 排序通讯录
  ///
  /// - Parameter chatUsers: 传入的用户数据模型
  /// - Returns: 返回排序好的用户模型和标题
  static func sortUser(chatUsers: [ChatUser]) -> ([[ChatUser]], [String]) {
    var sortedUserGroups: [[ChatUser]] = []
    var titles: [String] = []
    
    for index in 0..<27 {
      let array = [ChatUser]()
      sortedUserGroups.append(array)
      
      if 26 == index{
        titles.append("#")
        continue
      }
      
      let ASCII = index + 65
      let letter = ASCII.ASCII_CHAR
      titles.append(letter)
    }
    
    for chatUser in chatUsers {
      let first = chatUser.nickname.sj.chineseToPinYin().sj.cut(to: 1).uppercased()
      
      if first.sj.isLetter {
        let index = first.sj.ASCII - 65
        sortedUserGroups[index].append(chatUser)
      } else {
        sortedUserGroups[26].append(chatUser)
      }
    }
    
    for (index, group) in sortedUserGroups.enumerated() {
      if 0 == group.count {
        titles[index] = ""
      }
    }
    
    sortedUserGroups = sortedUserGroups.filter { (chatUsers) -> Bool in
      if chatUsers.count == 0 { return false }
      return true
    }
    
    titles = titles.filter({ (title) -> Bool in
      if title.isEmpty { return false }
      return true
    })
    
    return (sortedUserGroups, titles)
  }
}
